#version 300 es
precision mediump float;
uniform mat4 uMMatrix;

uniform float uR;
uniform vec3 uLightLocation;
uniform vec3 uLightDirection;
uniform vec3 uCamera;

in vec3 vNormal;
in vec3 vPosition;

out vec4 fragColor ;

vec3 getColor1(){
    vec3 color;
    float n = 8.0;
    float span = 2.0*uR/n;

    int i = int((vPosition.x + uR)/span);
    int j = int((vPosition.y + uR)/span);
    int k = int((vPosition.z + uR)/span);

    int whichColor = int(mod(float(i+j+k),2.0));

    if(whichColor == 1) {
    color = vec3(0.678,0.231,0.129);
    }else{
     color = vec3(1.0,1.0,1.0);
    }
    return color ;
}

void point(inout vec4 ambient){ //环境光设置
    ambient = vec4(0.15,0.15,0.15,1.0);
}

void point1(
in vec3 normal,
inout vec4 diffuse,
in vec3 lightLocation,
in vec4 lightDiffuse
){ //散射光设置
vec3 normalTarget=vPosition+normal;
vec3 newNormal=(uMMatrix*vec4(normalTarget,1)).xyz-(uMMatrix*vec4 (vPosition,1)).xyz;
newNormal=normalize(newNormal);
vec3 vp= normalize(lightLocation-(uMMatrix*vec4(vPosition,1)).xyz);
vp=normalize(vp);
float nDotViewPosition=max(0.0,dot(newNormal,vp));
diffuse=lightDiffuse*nDotViewPosition;
}

void point2(
in vec3 normal,
inout vec4 specular,
in vec3 lightLocation,
in vec4 lightSpecular
){ // 镜面光设置
vec3 normalTarget=vPosition+normal;  //
vec3 newNormal=(uMMatrix*vec4(normalTarget,1)).xyz-(uMMatrix*vec4(vPosition, 1)).xyz;
newNormal=normalize(newNormal);    //
vec3 eye= normalize(uCamera-(uMMatrix*vec4(vPosition,1)).xyz);//
vec3 vp= normalize(lightLocation-(uMMatrix*vec4(vPosition,1)).xyz);//
vp=normalize(vp);//
vec3 halfVector=normalize(vp+eye);//
float shininess=50.0;//
float nDotViewHalfVector=dot(newNormal,halfVector);//
float powerFactor=max(0.0,pow(nDotViewHalfVector,shininess));//
specular=lightSpecular*powerFactor;//
}

vec4 test(){
    vec4 ambientTemp=vec4(0.0,0.0,0.0,0.0);
    point(ambientTemp) ;
    return ambientTemp ;
}

vec4 test1(){

    vec4 diffuseTemp=vec4(0.0,0.0,0.0,0.0);
    point1(normalize(vNormal), diffuseTemp, uLightLocation, vec4(0.8,0.8,0.8,1.0));
    return diffuseTemp;

}
vec4 test2(){
    vec4 specularTemp=vec4(0.0,0.0,0.0,0.0);
    point2(normalize(vNormal), specularTemp, uLightLocation, vec4(0.7,0.7,0.7,1.0));
    return specularTemp;
}


void main(){
    vec4 finalColor = vec4( getColor1(),0);

  fragColor=finalColor*test() + finalColor*test1() + finalColor*test2();
}